package com.ubs.training.server.service;

import com.ubs.training.prod.server.service.LoggingService;
import com.ubs.training.server.dao.ClientDao;
import com.ubs.training.server.dao.model.Client;
import com.ubs.training.server.exception.ClientNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 12:59 PM
 * To change this template use File | Settings | File Templates.
 */
@Service
public class ClientService {
    public static final String USER_REQUESTS_ALL_CLIENTS = "User requests all clients";
    @Autowired
    @Qualifier("hbmClientDao")
    ClientDao dao;

    public ClientDao getDao() {
        return dao;
    }

    public void setDao(ClientDao dao) {
        this.dao = dao;
    }

    public List<Client> getAllClients() {
        return dao.getAll();
    }

    public void saveClient(Client client) {
        boolean result;
        if(client.getId() == 0) {
            result = dao.add(client);
        } else {
            Client orginalClient = dao.getById(client.getId());
            result = dao.update(client);
        }

        if(!result) {
            throw new ClientNotFoundException();
        }

    }

    public void remove(int clientId) {
        dao.remove(clientId);
    }

    public Client getById(int clientId) {
        try {
        return dao.getById(clientId);
        } catch (EmptyResultDataAccessException e) {
            throw new ClientNotFoundException(e);
        }
    }

}
